<template>
    <div class='message-container'>
        <div class="message-box" id="myDiv">
            <li class="message-item" v-for="message, index in messageList"
                :class="message.sendMemberId == memberVo.id ? 'message-right' : 'message-left'" v-if="isInclude(message.content)">
                <div v-if="checkShowHeadNickname(message, index)">
                    <div class="head-img">
                        <img @click="goMemberIndex(message.sendMemberId == memberVo.id ? memberVo.id : message.sendMemberId)"
                            :src="message.sendMemberId == memberVo.id ? memberVo.header : receiveMemberInfo.header" alt="">
                    </div>
                    <div class="nickname"
                        @click="goMemberIndex(message.sendMemberId == memberVo.id ? memberVo.id : message.sendMemberId)">
                        {{ message.sendMemberId == memberVo.id ? memberVo.nickname : receiveMemberInfo.nickname }}
                    </div>
                    <div class="nickname">
                        {{ getTime(message.createTime) }}
                    </div>
                </div>
                <div class="message-text" v-html="message.content">
                </div>
            </li>
        </div>
        <div class="text">
            <textarea class="msg-box" v-model="sendMsg.text" placeholder="请输入消息..."></textarea>
            <button class="enter" @click="sendMyMsg()">发送消息</button>
        </div>
    </div>
</template>
<script>

import getUUID from "../../utils/uuid"
import { timestampToTime } from "../../utils/util";

var webSocket = null;

var tempId = null;
var preTime = null;


export default {
    name: 'test',
    props: {
        receiveId: {   // 信息接收者的id
            default: ''
        }
    },
    data() {
        return {
            memberVo: [],   // 登陆会员信息
            sendMsg: {    // 信息对象
                to: '-1',
                data: new Date(),
                text: '',
                from: '',
            },
            messageList: [],   // 两者交流的信息集合
            sendMemberInfo: [],  // 发消息人的信息
            receiveMemberInfo: [],   // 接收人的信息
            url: null,


        };
    },
    components: {
    },
    computed: {
        webSocketMessage() {
            return this.sendMsg
        }
    },
    watch: {
        receiveId: {
            // 选择另一个人进行聊天时diaoyong
            async handler(val, oldVal) {
                this.getMemberInfo(this.receiveId)
                this.getMemberExchange()
                console.log("您将要吧信息发送给: ", this.receiveId)
                this.sendMsg.to = this.receiveId
                webSocket = new WebSocket(this.url);
            },
            deep: true
        }
    },
    methods: {

        isInclude(myStr) {
            return !myStr.includes('id="refundOption"')
        },

        getTime(time) {
            let nowTime = new Date().getTime()
            let day = 1000 * 60 * 60 * 24
            let temp = timestampToTime(time)
            let date = temp.substring(11)

            let computed = nowTime - time
            if (computed >= (day * 2) && computed < (day * 3)) {  // 前天
                date = "前天: " + date
            } else if (computed >= day && computed < (day * 2)) { // 昨天
                date = "昨天: " + date
            } else if (computed < day) {    // 今天
                return date
            } else {
                date = temp.substring(5)   // 大于前天的显示
            }
            return date
        },


        /**
         * 是否显示头像和用户名
         * 因为单个用户同时发送消息
         * @param {*} sendMemberId 
         */
        checkShowHeadNickname(message, index) {
            if (index == 0) {
                return true;
            }
            let sendMemberId = message.sendMemberId

            // 获得当前展示会员的id
            let nowId = sendMemberId == this.memberVo.id ? this.memberVo.id : sendMemberId
            let interval = 1000 * 60 * 10;  // 间隔10分钟

            // 当前信息为自己发送
            if (nowId == tempId) {
                if (message.createTime - preTime > interval) {
                    preTime = message.createTime
                    return true;
                }
                return false;
            } else {
                tempId = nowId;
                return true;
            }
        },


        /**
         * 前往用户首页
         * @param {*} id 
         */
        goMemberIndex(id) {
            if (id == this.memberVo.id) {
                if (window.location.href.includes("/member/membersetting/securitysetting")) {
                    this.$router.go(0);
                }
                this.$router.push({ path: '/member/membersetting/securitysetting' })
            } else {
                this.$router.push({
                    path: '/member/othermember',
                    query: {
                        memberId: id,
                        params: getUUID()
                    }
                })
            }
        },


        /**
         * 发送消息
         */
        async sendMyMsg() {
            // 不能发送空消息
            let a = this.sendMsg
            if (a.text == '' || a.text == null || a.text == undefined) {
                this.$message({
                    type: 'warning',
                    message: '不能发送空消息哦!'
                })
                return;
            }
            
            a.text = a.text.replaceAll("\n", "<br>")
            await webSocket.send(JSON.stringify(a))
            this.sendMsg.text = ''
            await this.getMemberExchange()

            var div = document.getElementById('myDiv');
            div.scrollTop = div.scrollHeight;
        },


        /**
         * 获取会员信息和初始化
         */
        async getInfo() {
            let member = await this.$memberInfo()
            if (member != null) {
                this.memberVo = member
                // 优先从请求参数里面获取
                let id = this.$route.query.temp_to
                if (id == null || id == undefined || id.length == 0 || id == member.id) {
                    // 判断父组件是否传过来id
                    id = this.receiveId
                    if (id == null || id == undefined || id.length == 0 || id == member.id) {
                        this.$router.go(-1)
                    }
                }
                this.sendMsg.to = this.receiveId
                this.sendMsg.from = this.memberVo.id
            }
        },


        /**
         * 获取两会员之间的所有信息
         */
        async getMemberExchange() {
            var div = document.getElementById('myDiv');
            div.scrollTop = div.scrollHeight;
            await this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/memberexchange/getMemberExchange?memberId=${this.memberVo.id}&receiveMemberId=${this.receiveId}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.messageList = data.data == null ? [] : data.data
                    if (this.messageList.length > 0) {
                        // 计算第一条信息是谁发的
                        if (data.data[0].sendMemberId == this.memberVo.id) {
                            // 当前登录用户发的
                            tempId = this.memberVo.id
                        } else {
                            // 接收者先发的
                            tempId = data.data[0].sendMemberId
                        }
                        // 第一条信息发送的时间
                        preTime = data.data[0].updateTime
                    }

                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 获取交流用户信息
         * @param {*} memberId 
         */
        async getMemberInfo(memberId) {
            await this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/member/getPublisher?memberId=${memberId}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.receiveMemberInfo = data.data
                }
            })
        },


        /**
         * 页面初始化
         */
        async init() {
            // 获取登录会员信息
            await this.getInfo()
            console.log("您将要吧信息发送给: ", this.receiveId)
            // 获取与之交流会员的信息
            await this.getMemberInfo(this.receiveId);
            // 获取的两个会员交流的记录
            await this.getMemberExchange()
        },

    },
    async created() {
        await this.init()
        this.url = `ws:${window.SITE_CONFIG.baseUrl.substring(5)}/shitou-member/shitou/room/${this.memberVo.id}`
        webSocket = new WebSocket(this.url);
        let this_ = this
        webSocket.onmessage = function (event) {
            var message = event;
            let msg = JSON.parse(message.data)
            // 处理消息
            this_.msg = msg.text
            // 获取两名会员之间发送和接收的所有信息
            this_.getMemberExchange()
        };
    },

    beforeDestroy() {
        webSocket.onclose = () => {
            console.log("断开连接")
        }
    },

}
</script>

<style scoped>
@import url("../../utils/css/exchange.css");
</style>

